package com.esb.transport.handler.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import com.esb.transport.handler.codec.serialization.Codec;


public class MessageDecoder extends LengthFieldBasedFrameDecoder {

	private Codec codec;
	
	public Codec getCodec() {
		return codec;
	}

	public void setCodec(Codec codec) {
		this.codec = codec;
	}

	public MessageDecoder() {
		super(1048576, 0, 2, 0, 2);
	}
	
	public MessageDecoder(Codec codec) {
		super(1048576, 0, 2, 0, 2);
		this.codec = codec;
	}

	protected Object decode(ChannelHandlerContext ctx, ByteBuf in)
			throws Exception {
		ByteBuf frame = (ByteBuf) super.decode(ctx, in);
		if (frame == null) {
			return null;
		}
		byte[] data = new byte[frame.readableBytes()];
		frame.readBytes(data);
		return codec.decode(data);//new ByteBufInputStream(frame));
	}

	protected ByteBuf extractFrame(ByteBuf buffer, int index, int length) {
		return buffer.slice(index, length);
	}

	/*@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, MessageBuf<Object> out) throws Exception {
		Object decoded = decode(ctx, in);
	    if (decoded != null)out.add(decoded);
	}*/

}
